package vn.sms.vsms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Calendar;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import vn.sms.vsms.data.ServiceItem;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Contants {
	
	public static String SMS_EXTRA_ID 	= "sms_extra_id";
	public static String SMS_AGENCY 	= "VHT";
	public static String SMS_PREFERENCE_VERSION 	=  "sms_preference";
	public static String SMS_AGENCY_PREFERENCE_VERSION 	=  "sms_agency_preference";
	public static String UPDATE_URL 	= "http://vms.vndone99.com/sms/service/checkversion/";
	public static final int HTTP_TIMEOUT = 30000;
	public static int getDayofWeek()
	{
		Calendar c = Calendar.getInstance();
	    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
	    switch (dayOfWeek) {
		case Calendar.SUNDAY:
			return 7;
		case Calendar.MONDAY:
			return 1;
		case Calendar.TUESDAY:
			return 2;	
		case Calendar.WEDNESDAY:
			return 3;
		case Calendar.THURSDAY:
			return 4;
		case Calendar.FRIDAY:
			return 5;
		case Calendar.SATURDAY:
			return 6;
		default:
			return 0;
		}
	}
	
	public static String getDeviceName() {
		  String manufacturer = Build.MANUFACTURER;
		  String model = Build.MODEL;
		  if (model.startsWith(manufacturer)) {
		    return capitalize(model);
		  } else {
		    return capitalize(manufacturer) + " " + model;
		  }
		}
	
	private static String capitalize(String s) {
		  if (s == null || s.length() == 0) {
		    return "";
		  }
		  char first = s.charAt(0);
		  if (Character.isUpperCase(first)) {
		    return s;
		  } else {
		    return Character.toUpperCase(first) + s.substring(1);
		  }
		} 
	
	public static void sendSMS(String structure,String extra,int phone)
	{
		String smsText = structure + getAgency();
		String model = getDeviceName();
		if(model != "")
		{
			model = model.replace(" ","-");
		}else
		{
			model = "not set";
		}
		
		smsText  = smsText +" " + model;
		
		if(!extra.isEmpty())
			smsText += " " + extra;
		//Toast.makeText(GlobalApplication._(),"sms:" + smsText + " ::phone:" + phone, Toast.LENGTH_LONG).show();
		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendTextMessage(String.valueOf(phone), null, smsText, null, null);
		Log.i("logging","sms:" + smsText + " ::phone:" + phone);
		
	}
	
	public static HttpClient getHttpClient() {
		HttpClient mHttpClient = new DefaultHttpClient();
		ClientConnectionManager mgr = mHttpClient.getConnectionManager();
		final HttpParams params = mHttpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
		ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
		ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
		ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
		ConnManagerParams.setMaxTotalConnections(params, 40);

		mHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(
				params, mgr.getSchemeRegistry()), params);

		return mHttpClient;
	}
	
	public static String downLoadUrlInBuffer(String url, int timeout){
	      BufferedReader in = null;
	      
	      try {
	          HttpClient client = getHttpClient();
	          HttpGet request = new HttpGet();
	          request.setURI(new URI(url));
	         
	          HttpResponse response = client.execute(request);
	          for(Header h : response.getAllHeaders())
	          {
	              Log.d(h.getName(),  h.getValue());
	          }
	          
	          StringBuffer sb = new StringBuffer("");
	          if(response.getEntity() != null) {
	              in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	             
	              String line = "";
	              while ((line = in.readLine()) != null) {
	                  sb.append(line);
	              }
	              in.close();
	          } else {
	              return null;
	          }
	          String result = sb.toString();
	          
	          return result;
	      } catch (Exception e) {
	          e.printStackTrace();
	      } 
	      finally {
	          if (in != null) {
	              try {
	                  in.close();
	              } catch (IOException e) {
	                  e.printStackTrace();
	              }
	          }
	      }
	      
	      return null;
	  }
	
	public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
	
	public static void onItemClick(Context mContext, final ServiceItem item)
	{
		 
			Log.v("logging","item:" + item.getName() + " "+ item.getIsguide());
			 if(item.getIsguide() > 0)
			 {
				 //huong dan
				 Intent intent = new Intent(mContext, GuideActivity.class );				 
				 mContext.startActivity(intent);
				 return;
			 }
			 else if(item.getParent() == 0){
				 // chuyen qua activity
				 Intent intent = new Intent(mContext, ListActivity.class );
				 intent.putExtra(Contants.SMS_EXTRA_ID,item.getId());
				 mContext.startActivity(intent);
				 return;
			 }
			 else if(item.getIspopup() > 0 ){
				 // gui tin nhan co input
				 Log.i("logging","sms popup");
				 LayoutInflater li = LayoutInflater.from(mContext);
				View promptsView = li.inflate(R.layout.prompts, null);
 
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						mContext);
 
				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);
				final TextView title 	= (TextView) promptsView.findViewById(R.id.dialog_title);
				if(item.getPopupTitle() != null)
				{
					title.setText(item.getPopupTitle());
				}
				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.dialog_input);
 
				// set dialog message
				alertDialogBuilder
					.setCancelable(false)
					.setPositiveButton("Đồng Ý",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
					    	String input 		=  userInput.getText().toString();
					    	if(input.isEmpty())
					    	{					    		
					    		AlertDialog.Builder builder = new AlertDialog.Builder(GlobalApplication._());
					    		builder.setTitle("Lỗi");					    		
					    		builder.setMessage("Nội dung rỗng");
					    		AlertDialog alertDialog = builder.create();
					    		alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
					    		alertDialog.show(); 
					    		return;
					    	}
					    	String structure 	= item.getStructure();
					    	int phone 			= item.getPhone();		
					    	Contants.sendSMS( structure,input, phone);
					    	
					    }
					  })
					.setNegativeButton("Hủy",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					    }
					  });
	 
					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();
	 
					// show it
					alertDialog.show();
				 
				 
			 }
			 else if(item.getPhone() > 0 )
			 {
				 // gui sms
				String structure 	=  item.getStructure();
		    	int phone 			=  item.getPhone();		
		    	Contants.sendSMS( structure,"",phone);
		    	
				 Log.i("logging","sms:" +item.getName());
				 
				 
			 }

	}
	
	public static String getAgency()
	{
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(GlobalApplication._());
		String agency 	= sharedPreferences.getString(Contants.SMS_AGENCY_PREFERENCE_VERSION, "");
		if(agency.isEmpty())
		{
			Editor edit = sharedPreferences.edit();
			edit.putString(Contants.SMS_AGENCY_PREFERENCE_VERSION,Contants.SMS_AGENCY);
			edit.commit();
			return Contants.SMS_AGENCY;
		}else
		{
			return agency;
		}
	}
	
	public static int getVersion()
	{
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(GlobalApplication._());
		int version = sharedPreferences.getInt(Contants.SMS_PREFERENCE_VERSION,0);
		return version;
	}
	
	 
	public static void updateVersion(int version)
	{
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(GlobalApplication._());
		Editor edit = sharedPreferences.edit();
		edit.putInt(Contants.SMS_PREFERENCE_VERSION,version);
		edit.commit();
	}
	
	
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
